package com.quickcancellation.crm.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.quickcancellation.crm.config.LogAspect;
import com.quickcancellation.crm.constant.enu.LoginStatus;
import com.quickcancellation.crm.constant.interfaceConstant.CommonConstant;
import com.quickcancellation.crm.pojo.dto.LoginDto;
import com.quickcancellation.crm.pojo.dto.ResponseDto;
import com.quickcancellation.crm.pojo.entity.Userinfo;
import com.quickcancellation.crm.pojo.vo.LeftMenuVo;
import com.quickcancellation.crm.service.IRoleService;
import com.quickcancellation.crm.service.IUserinfoService;
import com.quickcancellation.crm.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author 麦翔盛
 * @ClassName: UserController
 * @Package: com.quickcancellation.crm.controller
 * @description:
 * @date 2023/2/5 22:53
 */
@RestController
@CrossOrigin
@Api(tags = "权限管理")
public class UserController {

    @Resource
    private IUserinfoService userinfoService;

    @Resource
    private IRoleService roleService;
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private HttpServletRequest request;

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("doLogin")
    public SaResult doLogin(@RequestBody Map map) {

        String usernumber = MapUtils.getString(map, "usernumber");
        String password = MapUtils.getString(map, "password");

        // 判空
        if (!StringUtils.hasLength(usernumber)){
            return SaResult.error("用户名为空");
        }

        if (!StringUtils.hasLength(password)){
            return SaResult.error("密码为空");
        }

        LoginStatus status = userinfoService.login(usernumber, password);

        if (status.equals(LoginStatus.LOGIN_SUCCESS)) {
            String defaultMenuUrl = roleService.getDefaultMenu(usernumber);
            if (!StringUtils.hasLength(defaultMenuUrl)){
                return SaResult.error("您当前账号无任何权限");
            }

            StpUtil.login(usernumber);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            String token = tokenInfo.getTokenValue();

            // 获取默认菜单地址
            return SaResult.ok(token).setData(defaultMenuUrl);
        }

        if (status.equals(LoginStatus.LOGIN_PASSWORD_WRONG) || status.equals(LoginStatus.LOGIN_USER_NO_EXIST) ){
            return SaResult.error("用户名或密码错误");
        }

        if (status.equals(LoginStatus.LOGIN_STATUS_FAIL)){
            return SaResult.error("您的账号暂时无法使用");
        }


        return SaResult.error("登录失败");
    }


    @PostMapping("/getMenus")
    @ApiOperation("获取菜单")
    @SaCheckLogin
    public ResponseDto getMenus(){
        Userinfo userInfo = userinfoService.getUserInfoByRequest(request);
        String usernumber = userInfo.getUsernumber();


        List<LeftMenuVo> menus = roleService.getMenuListByUsernumber(usernumber);

        return ResponseUtil.success(menus.size(), menus);
    }


    /**
     * 根据token退出
     *
     * @param params token
     * @return 退出信息
     */
    @ApiOperation("根据token退出账号")
    @PostMapping("logoutByToken")
    @LogAspect
    public LoginDto logoutByTokenId(@RequestBody Map params) {
        String satoken = MapUtils.getString(params, CommonConstant.SA_TOKEN);

        StpUtil.logout(satoken);

        return LoginDto.logout();
    }

    @LogAspect
    @ApiOperation("获取用户基本信息")
    @PostMapping("/getBaseUserInfo")
    public ResponseDto   getBaseUserInfo(){

        Userinfo userInfo = userinfoService.getUserInfoByRequest(request);

        userInfo.setPassword(null);
        userInfo.setId(null);
        userInfo.setSex(userInfo.getSex().equals("1") ? "男":"女");
        userInfo.setStatus(userInfo.getStatus().equals("1") ? "正常":"禁用");


        return ResponseUtil.success(1,userInfo);
    }

    @LogAspect
    @ApiOperation("登录-不检验密码")
    @PostMapping("/login")
    public String login(@RequestBody Map map) {
        String userName = MapUtils.getString(map, "userName");
        String password = MapUtils.getString(map, "password");

        StpUtil.login(userName);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String tokenValue = tokenInfo.getTokenValue();

        return tokenValue;
    }

    @LogAspect
    @ApiOperation("是否登录-自定义登录响应")
    @PostMapping("/isLogin")
    public LoginDto isLogin() {

        String satoken = request.getHeader(CommonConstant.SA_TOKEN);

        String usernumber = StpUtil.getLoginIdByToken(satoken).toString();

        logger.info("用户usernumber:" + usernumber);

        Userinfo userInfo = userinfoService.getUserInfoByUserNumber(usernumber);

        logger.info("userInfo:[" + JSONObject.toJSONString(userInfo) + "]");

        boolean isLogin = StpUtil.isLogin();

        return isLogin ? LoginDto.success() : LoginDto.fail(-10002, "登录已过期或未登录");


    }

    @LogAspect
    @ApiOperation("查询用户名usernumber")
    @PostMapping("/getUsernumber")
    @SaCheckLogin
    public ResponseDto getUserInfo() {

        String satoken = request.getHeader(CommonConstant.SA_TOKEN);

        String usernumber = StpUtil.getLoginIdByToken(satoken).toString();

        logger.info("用户usernumber:" + usernumber);

        Userinfo userInfo = userinfoService.getUserInfoByUserNumber(usernumber);



        return ResponseUtil.success(0,userInfo.getUsername());


    }


    // 查询登录状态  ---- http://localhost:8081/acc/isLogin
    @ApiOperation("校验登录-官方")
    @PostMapping("checkLogin")
    public SaResult checkLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    // 查询 Token 信息  ---- http://localhost:8081/acc/tokenInfo
    @ApiOperation("tokenInfo-官方")
    @PostMapping("tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    // 测试注销  ---- http://localhost:8081/acc/logout
    @ApiOperation("退出-官方")
    @PostMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }


}
